package com.jxc.log;

import com.jxc.pojo.Log;
import com.jxc.service.LogService;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.aspectj.lang.ProceedingJoinPoint;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

public class LogAspect {//日志切面

    @Resource
    private LogService logService;
    /**
     * 添加日志  环绕通知
     * @param joinPoint
     * @return
     */
    public Object saveLog(ProceedingJoinPoint joinPoint){
        Object result = "";
        try {

            result = joinPoint.proceed();//保证业务继续执行
            //记录日志
            String methodName = joinPoint.getSignature().getName();//取出注解的名称
            System.out.println("methodName====="+methodName);

            Object[] args = joinPoint.getArgs();//方法中的参数数组

            Class<?> aClass = joinPoint.getTarget().getClass();//获取拦截到的类名称
            Method[] declaredMethods = aClass.getDeclaredMethods();
            String content = "";
            String type = "";
            for (Method m:declaredMethods
                 ) {
                if(m.getName().equals(methodName) && m.getParameterCount() == args.length){
                    JXCLog jxcLog = m.getDeclaredAnnotation(JXCLog.class);
                    content = jxcLog.operation();
                    type = jxcLog.type().getName();
                }
            }


            //取出注解中的信息, 添加日志表数据
            Log log = new Log();
            log.setContent(content);
            log.setTime(new Date());
            log.setType(type);
            log.setUserId(1);//用户ID从session域中取
            System.out.println("log==="+ ReflectionToStringBuilder.toString(log));
            //添加日志文件  存储到数据库中
            logService.insert(log);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return  result;
    }
}
